package com.example.rg.generator.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.rg.generator.commons.R;
import com.example.rg.generator.domain.Category;
import com.example.rg.generator.domain.Dish;
import com.example.rg.generator.service.CategoryService;
import com.example.rg.generator.service.DishService;
import com.example.rg.generator.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestControllerAdvice
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    public CategoryService categoryService;
    @Autowired
    public SetmealService setmealService;
    @Autowired
    public DishService dishService;

    //新增分类
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        log.info("category:{}", category);
        //添加数据
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    //分页查询
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        Page page1 = new Page<>(page, pageSize);
        //选择构造器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getSort);
        //分页查询
        categoryService.page(page1, lqw);
        return R.success(page1);
    }

    @DeleteMapping
    public R<String> delete(Long ids) {
        log.info("ids:{}", ids);
        //删除数据库数据
        categoryService.remove(ids);
        return R.success("删除成功");
    }

    @PutMapping
    public R<String> update(@RequestBody Category category) {
        log.info("Category:{}", category);
        //更新数据库数据
        categoryService.updateById(category);
        return R.success("分类添加成功");
    }

    /**
     * 根据条件查询分类数据
     *
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
//条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
//添加条件
        queryWrapper.eq(category.getType() !=
                null, Category::getType, category.getType());
//添加排序条件
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }

}
